<?php

namespace App\Services\Core\Sms\Dahan;


use App\Helpers\Logger\SLogger;
use App\Models\Factory\CacheFactory;
use App\Services\Core\Sms\SmsService;
use Log;


/**
 * 大汉短信通道
 * Class DahanService
 * @package App\Services\Core\Sms\Changzhuo
 */
class DahanService extends SmsService
{

    #请求地址
    const API_SEND_URL = 'http://www.dh3t.com/json/sms/Submit';

    const DAHAN_ACCOUNT = 'dh81271';

    #密码为80BLCta8的md5加密小写(32位)
    const DAHAN_PASSWORD = 'f8ab5153b09baffcf0c1740c506b64fc';

    /**
     * @param $mobile
     * @return string
     */
    public static  function send($mobile)
    {
        $code = rand(1000, 9999);
        $msg = "Harap masukkan kode verifikasi anda 【".$code."】";

        if (preg_match("/^08\d{7,10}$/u", $mobile)) {

            $postArr = json_encode(array(
                'account' => self::DAHAN_ACCOUNT,
                'password' => self::DAHAN_PASSWORD,
                'msgid' => $msg,
                'phones' => '+62'.$mobile,
                'content' => $msg,
                'sign' => '【Pinjaman Rupiah】',
                'subcode' => '',
                'sendtime' => '',
            ));

            $result = self::curlPost(self::API_SEND_URL, $postArr);
            SLogger::getStream()->info('这是大汉短信通道!');
            CacheFactory::putValueToCache($mobile . '_item_code', $code, 5 * 60);
            CacheFactory::putValueToCache($mobile . '_item_limit', $mobile, 60);

            return json_encode(array( "msg" => "短信验证码发送成功", "check" => $code));
        } else {
            return false;
        }
    }


    private static function curlPost($url, $postFields)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }
}
